package org.amos.core.frame.filter;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.MDC;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

import static org.amos.core.basic.constant.SystemConstant.TRACE_ID;

/**
 * @desc: log mdc 过滤器
 * @author: liubt
 * @date: 2022-08-26 09:42
 **/
@Order(Ordered.HIGHEST_PRECEDENCE)
@Component
public class LogFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String traceId = request.getHeader(TRACE_ID);
        if (StrUtil.isBlank(traceId)) {
            traceId = UUID.randomUUID().toString(true);
        }
        // 添加响应头
        response.setHeader(TRACE_ID, traceId);
        MDC.put(TRACE_ID, traceId);
        filterChain.doFilter(request, response);
        MDC.remove(TRACE_ID);
    }
}
